<template>
  <el-dialog
    :title="$t('project.editProject')"
    v-model="dialogVisible"
    width="500px"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-position="top"
      v-loading="loading"
    >
      <!-- 项目名称 -->
      <el-form-item :label="$t('project.name')" prop="name">
        <el-input 
          v-model="form.name" 
          :placeholder="$t('project.namePlaceholder')"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <!-- 项目描述 -->
      <el-form-item :label="$t('project.description')" prop="description">
        <el-input 
          v-model="form.description" 
          type="textarea" 
          :rows="4"
          :placeholder="$t('project.descriptionPlaceholder')"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <!-- 项目优先级 -->
      <el-form-item :label="$t('project.priority.description')" prop="priority">
        <el-select 
          v-model="form.priority" 
          class="w-100"
          :placeholder="$t('project.priorityPlaceholder')"
        >
          <el-option
            v-for="priority in priorityOptions"
            :key="priority.value"
            :label="priority.label"
            :value="priority.value"
          />
        </el-select>
      </el-form-item>

      <!-- 项目日期 -->
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item :label="$t('project.startDate')" prop="startDate">
            <el-date-picker
              v-model="form.startDate"
              type="datetime"
              :placeholder="$t('project.startDatePlaceholder')"
              class="w-100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('project.endDate')" prop="endDate">
            <el-date-picker
              v-model="form.endDate"
              type="datetime"
              :placeholder="$t('project.endDatePlaceholder')"
              class="w-100"
              :disabled-date="disabledEndDate"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 项目经理 -->
      <el-form-item :label="$t('project.manager')" prop="projectManagerId">
        <el-select 
          v-model="form.projectManagerId" 
          class="w-100"
          :placeholder="$t('project.managerPlaceholder')"
          filterable
          clearable
        >
          <el-option
            v-for="member in teamMembers"
            :key="member.userId"
            :label="member.username || member.nickname || `用户${member.userId}`"
            :value="member.userId"
          >
            <div class="member-option">
              <el-avatar :size="24" :src="member.avatarUrl">
                {{ (member.username || member.nickname || 'U')?.charAt(0).toUpperCase() }}
              </el-avatar>
              <span>{{ member.username || member.nickname || `用户${member.userId}` }}</span>
              <el-tag size="small" v-if="member.role === 'OWNER'">
                {{ $t('team.role.owner') }}
              </el-tag>
              <el-tag size="small" v-else-if="member.role === 'ADMIN'">
                {{ $t('team.role.admin') }}
              </el-tag>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 项目进度 -->
      <el-form-item :label="$t('project.progress')" prop="progress">
        <el-slider
          v-model="form.progress"
          :min="0"
          :max="100"
          :step="5"
          :format-tooltip="value => `${value}%`"
          :marks="{
            0: '0%',
            25: '25%',
            50: '50%',
            75: '75%',
            100: '100%'
          }"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ $t('common.save') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { projectApi } from '@/api/project'
import { useTeamStore } from '@/stores/teamStore'
import type { Project, ProjectUpdateRequest } from '@/types/project'
import { ProjectPriority } from '@/types/project'

// Props
interface Props {
  modelValue: boolean
  project: Project | null
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

const { t } = useI18n()
const teamStore = useTeamStore()

// 响应式数据
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref<FormInstance>()
const loading = ref(false)
const form = ref<ProjectUpdateRequest & { progress: number }>({
  name: '',
  description: '',
  priority: ProjectPriority.MEDIUM,
  startDate: undefined,
  endDate: undefined,
  projectManagerId: undefined,
  progress: 0
})

// 计算属性
const teamMembers = computed(() => {
  return teamStore.teamMembers.filter(member => 
    member.status === 'ACTIVE' && 
    (member.role === 'OWNER' || member.role === 'ADMIN')
  )
})

const priorityOptions = computed(() => [
  { value: ProjectPriority.LOW, label: t('project.priority.low') },
  { value: ProjectPriority.MEDIUM, label: t('project.priority.medium') },
  { value: ProjectPriority.HIGH, label: t('project.priority.high') },
  { value: ProjectPriority.URGENT, label: t('project.priority.urgent') }
])

// 表单验证规则
const rules = computed<FormRules>(() => ({
  name: [
    { required: true, message: t('project.nameRequired'), trigger: 'blur' },
    { min: 2, max: 100, message: t('project.nameLength'), trigger: 'blur' }
  ],
  description: [
    { max: 500, message: t('project.descriptionLength'), trigger: 'blur' }
  ],
  priority: [
    { required: true, message: t('project.priorityRequired'), trigger: 'change' }
  ],
  endDate: [
    { 
      validator: (rule, value, callback) => {
        if (value && form.value.startDate && new Date(value) < new Date(form.value.startDate)) {
          callback(new Error(t('project.endDateError')))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}))

// 方法
const disabledEndDate = (time: Date) => {
  if (!form.value.startDate) return false
  return time.getTime() < new Date(form.value.startDate).getTime()
}

const handleClose = () => {
  dialogVisible.value = false
}

const initForm = () => {
  if (!props.project) return
  
  form.value = {
    name: props.project.name,
    description: props.project.description || '',
    priority: props.project.priority as ProjectPriority,
    startDate: props.project.startDate,
    endDate: props.project.endDate,
    projectManagerId: props.project.projectManagerId,
    progress: props.project.progress
  }
}

const handleSubmit = async () => {
  if (!formRef.value || !props.project) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      loading.value = true
      
      // 格式化日期
      const formData = { ...form.value }
      delete formData.progress // 移除进度，通过单独的API更新

      await projectApi.updateProject(props.project!.id, formData)

      // 如果进度有变化，单独更新进度
      if (props.project!.progress !== form.value.progress) {
        // {{ AURA-X: Add - 调用项目进度更新API. Approval: 寸止(ID:fix-progress-update). }}
        await projectApi.updateProjectProgress(props.project!.id, form.value.progress)
      }
      
      ElMessage.success(t('project.updateSuccess'))
      emit('success')
      handleClose()
    } catch (error) {
      console.error('更新项目失败:', error)
      ElMessage.error(t('project.updateError'))
    } finally {
      loading.value = false
    }
  })
}

// 监听项目变化
watch(() => props.project, (newProject) => {
  if (newProject) {
    initForm()
  }
})

// 监听对话框打开
watch(dialogVisible, (visible) => {
  if (visible) {
    // 初始化表单
    initForm()
    
    // 加载团队成员
    if (teamStore.teamMembers.length === 0 && props.project) {
      teamStore.fetchTeamMembers(props.project.teamId)
    }
  }
})
</script>

<style scoped lang="scss">
.w-100 {
  width: 100%;
}

.member-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
